package apps

import (
	"sieve_admin_server_userpass/pkg/cache"
	"sieve_admin_server_userpass/pkg/im3/db"
	"sieve_admin_server_userpass/pkg/log"
)

var (
	c    = cache.PeriodLoad(db.LoaderPeriod, loadList)
	dbok = false
)

func init() {
	db.OnConnected(func() {
		dbok = true
		c.Load()
	})
}

type App struct {
	Aid      int
	Name     string
	Secret   string
	LoginUrl string
	Dept     int
}

func loadList() (list []*App) {
	list = []*App{}
	if !dbok {
		return
	}
	rows, err := db.Mysql().Query("SELECT `Aid`,`Name`,`Secret`,`LoginUrl`,`Dept` FROM `App` ORDER BY `Aid`")
	if err != nil {
		log.Err(err)
		return
	}
	defer rows.Close()
	for rows.Next() {
		a := &App{}
		if err := rows.Scan(
			&a.Aid,
			&a.Name,
			&a.Secret,
			&a.LoginUrl,
			&a.Dept,
		); err != nil {
			log.Err(err)
			return
		}
		list = append(list, a)
	}
	return
}

func Reload() {
	c.Load()
}

func GetAll() []*App {
	return c.Get()
}

func Get(id int) *App {
	for _, u := range c.Get() {
		if u.Aid == id {
			return u
		}
	}
	return nil
}
